import React, { useState, useRef } from "react";
import { Button, Card, Form, Input, InputNumber, message, Select } from "antd";
import { useNavigate } from "react-router-dom";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { useParams } from "react-router-dom";
import axios from "axios";
import { useEffect } from "react";
import PictureWall from "./picture_wall";
import RichTextEditor from "./rich_text_editor";
import { connect } from "react-redux";

const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 4,
    },
    md: {
      span: 4,
    },
    lg: {
      span: 4,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
    md: {
      span: 8,
    },
    lg: {
      span: 8,
    },
  },
};

const editorFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: {
      span: 16,
    },
    lg: {
      span: 16,
    },
  },
};

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 4,
    },
  },
};

function Update(props) {
  const navigate = useNavigate();
  let [cateList, setCateList] = useState([]);

  const [form] = Form.useForm();
  const richTextRef = useRef();
  const pictureRef = useRef();

  const { id } = useParams();
  const { userInfo } = props;

  const reqCateList = async () => {
    const responce = await axios.get(
      "http://api.shop.eduwork.cn/api/admin/category",

      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    // 因为添加分类时，只能用二级分类，一级分类无效，因此需遍历出所有二级分类id
    // 不能直接返回所有ID， 应该返回对象数组，这样用户才能选择名字，传给服务器id
    const resultArray = responce.data.map((item) => {
      return item.children;
    });

    const newCateList = resultArray.reduce((pre, cur) => {
      return [...pre, ...cur];
    });

    setCateList(newCateList);
  };

  const reqDetail = async (id) => {
    const responce = await axios.get(
      `http://api.shop.eduwork.cn/api/admin/goods/${id}`,

      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );
    const productObj = responce.data;
    form.setFieldsValue({
      title: productObj.title,
      price: productObj.price,
      stock: productObj.stock,
      category_id: productObj.category_id,
      description: productObj.description,
    });
    richTextRef.current.setRichText(productObj.details);
    const file = { url: productObj.cover_url, key: productObj.cover };
    const fileList = [file];
    pictureRef.current.handleChange({ fileList });
  };

  // 只能更新编辑自己新增的数据，对于系统原有的数据无法编辑，否则报错‘message: "系统数据禁止编辑, 请自行创建数据’
  const updateProduct = async (id, values) => {
    const responce = await axios.put(
      `http://api.shop.eduwork.cn/api/admin/goods/${id}`,
      values,

      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    if (responce.status === 204) {
      message.success("商品更新成功");
      navigate("/admin/product");
    } else {
      message.error(responce.data.message);
    }
  };

  // 根据richtexteditor返回的值更新form表单的值
  const setDetails = (content) => {
    form.setFieldsValue({ details: content });
  };

  const onFinish = (values) => {
    values.cover = values.cover[0].key;

    updateProduct(id, values);
  };

  const suffixSelector = (
    <Form.Item name="suffix" noStyle>
      <Select
        style={{
          width: 70,
        }}
      >
        <Option value="USD">$</Option>
        <Option value="CNY">¥</Option>
      </Select>
    </Form.Item>
  );

  useEffect(() => {
    reqCateList();

    if (props.productList.length === 0) {
      reqDetail(id);
    } else {
      // console.log("执行了");
      const productObj = props.productList.find((item) => {
        return item.id === id * 1;
      });
      form.setFieldsValue({
        title: productObj.title,
        price: productObj.price,
        stock: productObj.stock,
        category_id: productObj.category_id,
        description: productObj.description,
      });
      richTextRef.current.setRichText(productObj.details);
      const file = { url: productObj.cover_url, key: productObj.cover };
      const fileList = [file];
      pictureRef.current.handleChange({ fileList });
    }

    // eslint-disable-next-line
  }, []);

  return (
    <div>
      <Card
        title={
          <div className="detail-top">
            <Button
              type="link"
              onClick={() => {
                navigate(-1);
              }}
            >
              <ArrowLeftOutlined style={{ fontSize: "20px" }} />
            </Button>
            <span> 修改商品</span>
          </div>
        }
      >
        <Form
          {...formItemLayout}
          form={form}
          name="register"
          onFinish={onFinish}
          scrollToFirstError
        >
          <Form.Item
            name="title"
            label="商品名称"
            rules={[
              {
                required: true,
                message: "Please input product title!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="description"
            label="商品描述"
            rules={[
              {
                required: true,
                message: "Please input product description!",
                //whitespace: true,
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="category_id"
            label="商品类别"
            rules={[
              {
                required: true,
                message: "Please select category_id!",
              },
            ]}
          >
            <Select placeholder="select category_id">
              {cateList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="price"
            label="商品价格"
            rules={[
              {
                required: true,
                message: "Please input product price!",
              },
            ]}
          >
            <InputNumber
              addonAfter={suffixSelector}
              style={{
                width: "100%",
              }}
            />
          </Form.Item>

          <Form.Item
            name="stock"
            label="商品库存"
            rules={[
              {
                required: true,
                message: "Please input product stock!",
              },
            ]}
          >
            <InputNumber
              style={{
                width: "100%",
              }}
            />
          </Form.Item>

          <Form.Item
            name="cover"
            label="商品图片"
            rules={[
              {
                required: true,
                message: "Please input product pic!",
              },
            ]}
          >
            <PictureWall ref={pictureRef}></PictureWall>
          </Form.Item>

          <Form.Item
            {...editorFormItemLayout}
            name="details"
            label="商品详情"
            rules={[
              {
                required: true,
                message: "Please input product detail",
              },
            ]}
          >
            <RichTextEditor setDetails={setDetails} ref={richTextRef} />
          </Form.Item>

          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default connect((state) => ({
  userInfo: state.userInfo,
  productList: state.proInfo,
}))(Update);
